package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.AllTheException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

import static com.sky.constant.MessageConstant.LOGIN_FAILED;

/**
 * @Author：XueShiHao
 * @Date：2025/6/20 星期五 13:49:57
 * @Email:747278007@qq.com
 * @Description:
 **/
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatProperties weChatProperties;
    //微信接口服务地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    /**
     * 微信登录
     *
     * @param userLoginDTO
     * @return
     */
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
String openId=getOpenId(userLoginDTO.getCode());
if(openId==null){
    throw new AllTheException(LOGIN_FAILED );
}
User user=userMapper.getById(openId);
if(user==null){//判读那是否为新用户，是则自动完成注册
    user=User.builder()
            .openid(openId)
                    .createTime(LocalDateTime.now())
            .build();
    userMapper.insert(user);
}

        return user;
    }

    /**
     * 调用微信接口服务，获取微信用户的OpenId
     * @param code
     * @return
     */
    private String getOpenId(String code){
        Map<String ,String> map=new HashMap<>();
        map.put("appId", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        String json= HttpClientUtil.doGet(WX_LOGIN,map);
        JSONObject jsonObject= JSON.parseObject(json);
        String openId=jsonObject.getString("openId");
        return openId;
    }
}
